package com.jxmcloud.business.cut.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class RedissonConfig {

    @Resource
    private RedisProperties redisProperties;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.setCodec(JsonJacksonCodec.INSTANCE);

        if (redisProperties.getSentinel() != null) {
            config.useSentinelServers()
                    .setKeepAlive(true)
                    .setPingConnectionInterval(10000)
                    .setMasterName(redisProperties.getSentinel().getMaster())
                    .setDatabase(redisProperties.getDatabase())
                    .addSentinelAddress(redisProperties.getSentinel().getNodes().stream().map("redis://"::concat).toArray(String[]::new));
        } else {
            config.useSingleServer()
                    .setKeepAlive(true)
                    .setPingConnectionInterval(10000)
                    .setAddress(String.format("redis://%s:%s", redisProperties.getHost(), redisProperties.getPort()))
                    .setPassword(redisProperties.getPassword())
                    .setDatabase(redisProperties.getDatabase());
        }
        return Redisson.create(config);
    }

}
